package org.Lin.launcher;

import org.Lin.controller.MainServerController;

import java.io.*;
import java.net.*;
import org.json.JSONObject;

public class ServerLauncher {

    private static final int PORT = 5545;

    public static void main(String[] args) {
        System.out.println("正在启动聊天中心服务端...");
        try (ServerSocket serverSocket = new ServerSocket(PORT,50,InetAddress.getByName("0.0.0.0"))) {
            System.out.println("服务端已启动，监听端口: " + PORT);

            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(() -> handleClient(socket)).start();
            }

        } catch (IOException e) {
            System.err.println("服务端启动失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket socket) {
        try (
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
        ) {
            String encryptedData = in.readLine();
            if (encryptedData == null || encryptedData.isEmpty()) {
                return;
            }

            // 解密数据
            String decryptedData = org.Lin.util.AESUtil.decrypt(encryptedData);
            JSONObject request = new JSONObject(decryptedData);

            // 分发请求
            MainServerController controller = new MainServerController();
            controller.handleRequest(request, socket);

        } catch (Exception e) {
            System.err.println("处理客户端请求时出错: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (socket != null && !socket.isClosed()) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
